package scala.for_the.impatient

import scala.math.{ceil, sqrt}

/**
  * Created by shichen on 2017/5/24.
  */

class HighScaleFunc {
  def t(): Unit = {
    var fun = ceil _

    val num = 3.14
    println(fun(num))
    Array(3.14,1.42,2.0).map(fun) //map接受数组所有值，返回结果数组

    val triple = (x:Double) => 3*x
    println(Array(3.14,1.42,2.0).map((x:Double) => 3*x))

    println("hight scale func:")
    println(valueAtOneQuarter(ceil))
    println(valueAtOneQuarter(sqrt))

    val f2 = mulBy(2)
    println(f2(20))

    //当只有一个函数参数时，(x) => 3*x中的()可省，如果右侧x只使用一次
    //可直接用_代替
    println((1 to 9).map(0.1 * _))
    (1 to 9).map("*" * _).foreach(println _)

    (1 to 9).filter(_ % 2 == 0).foreach(println _)
    println((1 to 9).reduceLeft(_ * _)) //1*2*3...*9

    //返回排好序的Array[String]
    "Mary hav a little lamb".split(" ").sortWith(_.length < _.length)
  }

  //接收函数参数的函数称为高阶函数
  def valueAtOneQuarter(f: (Double) => Double) = f(0.25)

  def mulBy(factor:Double) = (x:Double) => factor*x
}

object ch12_highorder_func extends App{
  def t_high_scale_func(): Unit = {
    val highScaleFunc = new HighScaleFunc
    highScaleFunc.t()
  }
}
